<template>
  <a-modal title="修改角色" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="roleEditVisiable">
    <a-form-item label="id" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help" style="display: none">
      <a-input v-decorator="['id']" />
    </a-form-item>
    <a-form-item label="法人行号" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['instId']" />
    </a-form-item>
    <a-form-item label="机构号" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['orgCode']" />
    </a-form-item>
    <a-form-item label="创建机构号" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['crtOrgId']" />
    </a-form-item>
    <a-form-item label="创建人" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['oprId']" />
    </a-form-item>
    <a-form-item label="创建时间" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['createTime']" />
    </a-form-item>
    <a-form-item label="最后修改人" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['lastOprId']" />
    </a-form-item>
    <a-form-item label="最后修改时间" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
      style="display: none">
      <a-input v-decorator="['lastUpdateTime']" />
    </a-form-item>
    <a-form-item label="状态" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help" style="display: none">
      <a-input v-decorator="['status']" />
    </a-form-item>
    <a-form-item label="角色级别" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help">
      <a-select disabled mode="default" :allowClear="true" style="width: 100%" :default-value="roleInfoData.roleCode"
        v-decorator="['roleCode', { rules: [{ required: true, message: '请选择角色级别' }] }]">
        <a-select-option v-for="r in roleCodeData" :key="r.label">{{ r.value }}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form :form="form">
      <a-form-item label='角色名称' v-bind="formItemLayout" :validateStatus="validateStatusRoleName" :help="helpRoleName">
        <a-input @blur="handleRoleNameBlur"
          v-decorator="['roleName', { rules: [{ required: true, message: '请输入角色名称' }] }]" />
      </a-form-item>
      <a-form-item label='角色描述' v-bind="formItemLayout">
        <a-textarea :rows="4" v-decorator="[
        'roleDesc',
        {
          rules: [
            { max: 50, message: '长度不能超过50个字符' }
          ]
        }]">
        </a-textarea>
      </a-form-item>
      <a-form-item label='权限选择' style="margin-bottom: 4rem!important;" :validateStatus="menuSelectStatus"
        :help="menuSelectHelp" v-bind="formItemLayout">
        <a-tree :key="menuTreeKey" ref="menuTree" :checkable="true" :checkStrictly="checkStrictly"
          :defaultCheckedKeys="defaultCheckedKeys[0]" @check="handleCheck" @expand="handleExpand"
          :expandedKeys="expandedKeys" :treeData="menuTreeData">
        </a-tree>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="2" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          菜单树
          <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'RoleEdit',
  props: {
    roleEditVisiable: {
      default: false
    },
    roleInfoData: {
      require: true
    },
    roleInstId: '',
    roleCodeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      help: '',
      menuTreeKey: +new Date(),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      menuSelectStatus: '',
      menuSelectHelp: '',
      role: {
        menuId: ''
      },
      menuTreeData: [],
      allTreeKeys: [],
      checkedKeys: [],
      defaultCheckedKeys: [],
      expandedKeys: [],
      validateStatus: '',
      validateStatusRoleName: '',
      helpRoleName: '',
      checkStrictly: false,
      orgRoleName: ''
    }
  },
  computed: {
    show: {
      get: function () {
        return this.roleEditVisiable
      },
      set: function () {
      }
    }
  },
  methods: {
    reset() {
      this.menuTreeKey = +new Date()
      this.expandedKeys = []
      this.checkedKeys = []
      this.defaultCheckedKeys = []
      this.menuSelectStatus = this.menuSelectHelp = ''
      this.loading = false
      this.form.resetFields()
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    handleCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
      let checkedArr = Object.is(checkedKeys.checked, undefined) ? checkedKeys : checkedKeys.checked
      if (checkedArr.length) {
        this.menuSelectStatus = ''
        this.menuSelectHelp = ''
      } else {
        this.menuSelectStatus = 'error'
        this.menuSelectHelp = '请选择相应的权限'
      }
    },
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    setFormValues({ ...role }) {
      let fields = ['id', 'instId', 'orgCode', 'status', 'roleName', 'roleDesc', 'crtOrgId', 'oprId', 'createTime', 'lastOprId', 'lastUpdateTime']
      // let fields = ['id','instId','orgCode','status','roleCode','roleName', 'roleDesc','crtOrgId','oprId','createTime','lastOprId','lastUpdateTime']

      Object.keys(role).forEach((key) => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          let obj = {}
          obj[key] = role[key]
          this.form.setFieldsValue(obj)
          if (key == 'roleName') {
            this.orgRoleName = role[key];
          }
        }
      })
    },
    async handleRoleNameBlur () {
        this.validateStatusRoleName = 'success'
        this.helpRoleName = ''
        let roleName = this.form.getFieldValue('roleName')
        roleName = typeof roleName === 'undefined' ? '' : roleName.trim()
        if (roleName.length) {
            if (roleName.length > 10) {
                this.validateStatusRoleName = 'error'
                this.helpRoleName = '角色名称不能超过10个字符'
            } else {
                if(this.orgRoleName != roleName ) {
                    this.validateStatusRoleName = 'validating'
                    const res = await this.$get(`admin/upmprole/check`,{
                        instId:this.roleInstId,
                        roleName:roleName
                    });
                    if (res.data.status) {
                        this.validateStatusRoleName = 'success'
                        this.helpRoleName = ''
                    } else {
                        this.validateStatusRoleName = 'error'
                        this.helpRoleName = '抱歉，该角色名称已存在'
                    }
                }
            }
        } else {
            this.validateStatusRoleName = 'error'
            this.helpRoleName = '角色名称不能为空'
        }
    },
    handleSubmit() {
      this.handleRoleNameBlur();
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked
      if (this.validateStatusRoleName == 'error') {

      } else if (checkedArr.length === 0) {
        this.menuSelectStatus = 'error'
        this.menuSelectHelp = '请选择相应的权限'
      } else {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true
            let role = this.form.getFieldsValue()
            role.id = this.roleInfoData.id
            role.instId = this.roleInfoData.instId
            role.status = this.roleInfoData.status
            role.crtOrgId = this.roleInfoData.crtOrgId
            role.oprId = this.roleInfoData.oprId
            role.createTime = this.roleInfoData.createTime
            role.lastOprId = this.roleInfoData.lastOprId
            role.lastUpdateTime = this.roleInfoData.lastUpdateTime
            role.menuId = checkedArr.join(',')
            this.$put('admin/upmprole', {
              ...role
            }).then((res) => {
              if (res.status === 200) {
                this.$emit('success')
                this.loading = false
                return true;
              } else {
                this.$message.error(res.data.message);
                return false;
              }
            }).catch(() => {
              this.loading = false
            })
          }
        })
      }
    }
  },
  watch: {
    roleEditVisiable() {
      if (this.roleEditVisiable) {
        this.$get('admin/upmpmenu', {
          channelType: '00'
        }).then((r) => {
          this.menuTreeData = r.data.rows.children
          this.allTreeKeys = r.data.ids
          this.$get('admin/upmprole/menu/' + this.roleInfoData.id).then((r) => {
            this.defaultCheckedKeys.splice(0, this.defaultCheckedKeys.length, r.data)
            this.checkedKeys = r.data
            this.expandedKeys = r.data
            this.menuTreeKey = +new Date()
          })
        })
      }
    }
  }
}
</script>
